package com.cyan.app.workflow.activity.WHM;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.cyan.app.barcode.CaptureActivity;
import com.cyan.app.workflow.AppData;
import com.cyan.app.workflow.R;
import com.cyan.app.workflow.base.activity.BaseActivity;
import com.cyan.app.workflow.bean.BaseBean;
import com.cyan.app.workflow.bean.PurOrderAcceptBean.PurOrderAccept;
import com.cyan.app.workflow.bean.PurOrderAcceptBean;
import com.cyan.app.workflow.bean.WHouseBean;
import com.cyan.app.workflow.common.HttpConfig;
import com.cyan.app.workflow.customview.PullDownView;
import com.cyan.app.workflow.customview.PullDownView.OnPullDownListener;
import com.cyan.app.workflow.util.AppUtils;
import com.cyan.app.workflow.util.network.CommHttpListener;
import com.cyan.app.workflow.util.network.VolleyUtil;

//import org.json.JSONObject;
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by GK on 2020/02/14.
 */
/*采购扫码入库 */
public class PurWhScanActivitiy extends BaseActivity implements OnPullDownListener, AdapterView.OnItemClickListener {
    public static final String TAG = "PurWhScanActivitiy";
    private TextView mTextView;
    private Button mButton;
    private RelativeLayout mRelativeLayout;
    private ListView mannoinfo_lv;
    private PullDownView mPullDownView;
    private Button buttonScan;
    private Button buttonconfirm;


    private EditText PurOrder_fin;
    private List<WHouseBean.InvWarehouse> mWHouseBeans = new ArrayList<WHouseBean.InvWarehouse>();
   private  ArrayList<String> listProssName  = new ArrayList<String>();
    private  Spinner spinner1;

    private EditText editItemNumber;
    private EditText editItemName;
    private  EditText editItemSpec;
    private  EditText editPurunit;

    private  EditText editorQty;
    private EditText Hidmsg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.purchase_and_warehousing);//设置显示界面 实例化显示界面的按钮 添加相关事件
        PurOrder_fin = (EditText)findViewById(R.id.PURORder_fin);//扫描输入栏 识别二维码 或者手动输入
        editItemNumber  = (EditText)findViewById(R.id.bms_barcodefin_itemnumber);

        editItemName  = (EditText)findViewById(R.id.bms_barcodefin_itemname);
        editItemSpec = (EditText)findViewById(R.id.bms_barcodefin_itemspec);
        editPurunit = (EditText)findViewById(R.id.purunit);
        editorQty = (EditText)findViewById(R.id.puracc_qty);
        Hidmsg=(EditText)findViewById(R.id.hid_msg);
        editItemNumber.setInputType(InputType.TYPE_NULL);
        editItemNumber.setTextColor(Color.GRAY);

       // editProcedureName.setInputType(InputType.TYPE_NULL);
     //   editProcedureName.setTextColor(Color.GRAY);

        editItemName.setInputType(InputType.TYPE_NULL);
        editItemName.setTextColor(Color.GRAY);

        editItemSpec.setInputType(InputType.TYPE_NULL);
        editItemSpec.setTextColor(Color.GRAY);
        editPurunit.setInputType(InputType.TYPE_NULL);
        editPurunit.setTextColor(Color.GRAY);

        editorQty.setInputType(InputType.TYPE_NULL);
        editorQty.setTextColor(Color.GRAY);


        spinner1 = (Spinner) findViewById(R.id.pross_spinner);

        initData();
        initView();
      //  EditText searchView = (EditText) findViewById(R.id.search_text);

        PurOrder_fin.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                //当actionId == XX_SEND 或者 XX_DONE时都触发
                //或者event.getKeyCode == ENTER 且 event.getAction == ACTION_DOWN时也触发
                //注意，这是一定要判断event != null。因为在某些输入法上会返回null。
                if ((event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())) {

                    getBmsBarocdeInfo(PurOrder_fin.getText().toString());

                    return true;
                }
                return false;
            }
        });

        //确认按钮点击事件
        buttonconfirm = (Button)findViewById(R.id.bms_btn_confirm);
        buttonconfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if(!AppData.getInstance().isUserLogin()) return;
                    Map<String, String> params = new HashMap<String, String>();
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("FactoryID", HttpConfig.Main_FactoryID);
                    jsonObject.put("FacNo", HttpConfig.Main_FacNo);
                    jsonObject.put("UserNo", AppData.getInstance().getUserId());
                    jsonObject.put("Connectstring", AppData.getInstance().getConnectstring());
                    jsonObject.put("PurOrderDetailNo", PurOrder_fin.getText().toString( ));
                    //如何将数据保存 隐藏控件 json?
                    //JSONObject.toJavaObject((JSON)Hidmsg.getText().toString(),PurOrderAcceptBean.class);
                    String sdf=Hidmsg.getText().toString();
            //        jsonObject.put("hidmsg",sdf);
                    jsonObject.put("AcceptQty", editorQty.getText().toString( ));
                    String dfs=  Hidmsg.getText().toString();
                    if(mWHouseBeans.size()>0) {
                        jsonObject.put("OIDWareh", mWHouseBeans.get(spinner1.getSelectedItemPosition()).getOID());
                    }
                    params.put("paramstr", jsonObject.toString());
                    params.put("action", "PurAccSvAndCfm");//在此处理 扫码入库逻辑
                    VolleyUtil.sendStringRequestByGet(PurWhScanActivitiy.this, HttpConfig.HTTP_MAIN_API_URL, TAG, params, BaseBean.class, new CommHttpListener<BaseBean>() {
                        @Override
                        public void onSuccess(BaseBean baseBean) {
                            AppUtils.showTip(PurWhScanActivitiy.this, baseBean.getMsg());
                            PurOrder_fin.setText("");
                            editItemNumber.setText("");
                            editItemName.setText("");
                            editPurunit.setText("");
                           // editProcedureName.setText("");
                            editorQty.setText("");
                        }

                        @Override
                        public void onCodeError(int code, String msg) {
                            AppUtils.showTip(PurWhScanActivitiy.this, msg);
                        }

                        @Override
                        public void onVolleyError(VolleyError volleyError) {
                            AppUtils.showTip(PurWhScanActivitiy.this, R.string.network_error);
                        }

                        @Override
                        public void onException(Exception e) {
                            AppUtils.showTip(PurWhScanActivitiy.this, R.string.network_error);
                        }
                    });
                }catch (Exception e){
                    e.printStackTrace();
                    AppUtils.showTip(PurWhScanActivitiy.this, "执行失败，请联系IT人员");
                }


            }
        });
        //扫描监听事件
        buttonScan = (Button) findViewById(R.id.bms_barcodefin_scan);
        buttonScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(PurWhScanActivitiy.this, CaptureActivity.class), 0x0002);
            }
        });

    }

    private void initData() {
        //获取仓库信息
        try {
            if(!AppData.getInstance().isUserLogin()) return;
            Map<String, String> params = new HashMap<String, String>();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("FactoryID", HttpConfig.Main_FactoryID);
            jsonObject.put("FacNo", HttpConfig.Main_FacNo);
            jsonObject.put("UserNo", AppData.getInstance().getUserId());
            jsonObject.put("Connectstring", AppData.getInstance().getConnectstring());
            params.put("action", "GetWareh");//行为参数在这里传入方法 在ashx 文件中处理并返回相应数据 获取仓库信息
            params.put("paramstr", jsonObject.toString());
            VolleyUtil.sendStringRequestByGet(PurWhScanActivitiy.this, HttpConfig.HTTP_MAIN_API_URL, TAG, params, WHouseBean.class, new CommHttpListener<WHouseBean>() {
                @Override
                public void onSuccess(WHouseBean prossBean) {

                    //  mProssBeans = new Gson().fromJson(result, new TypeToken<List<ProssBean>>() {
//                    }.getType());
                    mWHouseBeans = prossBean.getResult();
                    for(WHouseBean.InvWarehouse obj : mWHouseBeans){
                        listProssName.add(obj.getWhDsc());
                    }

                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(PurWhScanActivitiy.this,android.R.layout.simple_spinner_item, listProssName);
                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    spinner1 .setAdapter(adapter);
                    spinner1.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view,
                                                   int pos, long id) {

                            //String[] languages = getResources().getStringArray(R.array.languages);
                           // AppUtils.showTip(BarcodeRecieveScanActivitiy.this,  mProssBeans.get(pos).getProcedureNo());
                        }
                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {
                            // Another interface callback
                        }
                    });
                }

                @Override
                public void onCodeError(int code, String msg) {
                    AppUtils.showTip(PurWhScanActivitiy.this, msg);
                }

                @Override
                public void onVolleyError(VolleyError volleyError) {
                    AppUtils.showTip(PurWhScanActivitiy.this, R.string.network_error);
                }

                @Override
                public void onException(Exception e) {
                    AppUtils.showTip(PurWhScanActivitiy.this, R.string.network_error);
                }
            });
        }catch (Exception e){
            e.printStackTrace();
            AppUtils.showTip(PurWhScanActivitiy.this, "执行失败，请联系IT人员");
        }


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 0x0002 && resultCode == RESULT_OK) {
            String result = "";
            if(data != null) {
                result = data.getStringExtra("result");
                getBmsBarocdeInfo(result);
            }

        }
    }

    private void getBmsBarocdeInfo(String barcode){//采购单号-行项目
        String result = null;
        try {
            Map<String, String> params = new HashMap<String, String>();
            final JSONObject jsonObject = new JSONObject();
            jsonObject.put("Barcode", barcode);//采购单明细
            jsonObject.put("FactoryID", HttpConfig.Main_FactoryID);
            jsonObject.put("UserNo", AppData.getInstance().getUserId());
            jsonObject.put("Connectstring", AppData.getInstance().getConnectstring());
            params.put("action", "GetPurOrderDetail");//获取采购明细 并带出相关数据
            params.put("paramstr", jsonObject.toString());
            VolleyUtil.sendStringRequestByGet(PurWhScanActivitiy.this, HttpConfig.HTTP_MAIN_API_URL, TAG, params, PurOrderAcceptBean.class, new CommHttpListener<PurOrderAcceptBean>() {
                public void onSuccess(PurOrderAcceptBean bmsBarcodeBean) {
                    List<PurOrderAccept> purOrderAccepts;
                    purOrderAccepts = bmsBarcodeBean.getResult();

                    if(purOrderAccepts.size()>0){

                        PurOrder_fin.setText(purOrderAccepts.get(0).getPurOrderDetailNo());
                        editItemNumber.setText(purOrderAccepts.get(0).getItemNumber());//品号
                        editItemName.setText(purOrderAccepts.get(0).getItemName());//品名
                       // FloatingDecimal.getThreadLocalInstance().loadDouble(d).toJavaFormatString()
                        editPurunit.setText(purOrderAccepts.get(0).getPurUnit());//单位

                        String qt=""+purOrderAccepts.get(0).getRemainingAcceptQty();//数量
                        editorQty.setText(qt);
                         editItemSpec.setText(purOrderAccepts.get(0).getItemSpec());//规格

                    }
                    else{
                        AppUtils.showTip(PurWhScanActivitiy.this, "无效条码，请扫码正确的条码");
                        PurOrder_fin.setText("");
                    }
                }

                @Override
                public void onCodeError(int code, String msg) {
                    AppUtils.showTip(PurWhScanActivitiy.this, msg);
                    PurOrder_fin.setText("");
                }

                @Override
                public void onVolleyError(VolleyError volleyError) {
                    AppUtils.showTip(PurWhScanActivitiy.this, R.string.network_error);
                    PurOrder_fin.setText("");
                }

                @Override
                public void onException(Exception e) {
                    AppUtils.showTip(PurWhScanActivitiy.this, R.string.network_error);
                    PurOrder_fin.setText("");
                }
            });
        }catch (Exception e){
            e.printStackTrace();
            AppUtils.showTip(PurWhScanActivitiy.this, "执行失败，请联系IT人员");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
       // adapter.notifyDataSetChanged();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    private void initView(){
        titleBar();
        /*
		 * 1.使用PullDownView 2.设置OnPullDownListener 3.从mPullDownView里面获取ListView
		 */

    }

    private void titleBar() {
        mTextView =(TextView)findViewById(R.id.top_title_info);
        mTextView.setText("采购扫码收货");
        Button back = (Button) findViewById(R.id.top_title_back);
        back.getBackground().setAlpha(255);// 透明度0~255透明度值 ，值越小越透明
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //返回按钮
                finish();
            }
        });
        mButton = (Button)findViewById(R.id.top_title_refres_with_icon);
        mButton.setVisibility(View.VISIBLE);

        mRelativeLayout =(RelativeLayout) findViewById(R.id.bms_barcodefin_scan_footer);
        mRelativeLayout.setVisibility(View.VISIBLE);
    }

    /**
     * listview单项点击事件
     */
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // Toast.LENGTH_SHORT).show();
    }

    /**
     * listview刷新
     */
    public void onRefresh() {

    }

    /**
     * listview更多
     */
    public void onMore() {
      return;
    }



}
